﻿using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CWM.Client.Utils
{
    internal class ExcelHelper
    {
        /// <summary>
        /// Excel导入成Datable
        /// </summary>
        /// <param name="file">导入路径(包含文件名与扩展名)</param>
        /// <param name="mapping">字段映射</param>
        /// <returns></returns>
        public static DataTable ExcelToTable(string file, Dictionary<string, string> mapping)
        {
            DataTable dt = ExcelToTable(file);
            DataTable dt2 = new DataTable();
            //表头
            foreach (var item in mapping)
            {
                dt2.Columns.Add(new DataColumn(item.Value));
            }
            //数据
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt2.NewRow();

                foreach (var item in mapping)
                {
                    if (dt.Columns.Contains(item.Key))
                    {
                        dr[item.Value] = dt.Rows[i][item.Key];
                    }
                    else
                    {
                        dr[item.Value] = null;
                    }
                }
                dt2.Rows.Add(dr);
            }
            return dt2;
        }

        /// <summary>
        /// Excel导入成Datable
        /// </summary>
        /// <param name="file">导入路径(包含文件名与扩展名)</param>
        /// <returns></returns>
        public static DataTable ExcelToTable(string file)
        {
            DataTable dt = new DataTable();
            IWorkbook workbook;
            string fileExt = System.IO.Path.GetExtension(file).ToLower();
            using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                //XSSFWorkbook 适用XLSX格式，HSSFWorkbook 适用XLS格式
                if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(fs); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(fs); } else { workbook = null; }
                if (workbook == null) { return null; }
                ISheet sheet = workbook.GetSheetAt(0);

                //表头
                IRow header = sheet.GetRow(sheet.FirstRowNum);
                List<int> columns = new List<int>();
                for (int i = 0; i < header.LastCellNum; i++)
                {
                    object obj = GetValue(header.GetCell(i));
                    if (obj == null || obj.ToString() == string.Empty)
                    {
                        dt.Columns.Add(new DataColumn("column" + i.ToString()));
                    }
                    else
                    {
                        dt.Columns.Add(new DataColumn(obj.ToString()));
                    }
                    columns.Add(i);
                }
                //数据
                for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
                {
                    DataRow dr = dt.NewRow();
                    bool hasValue = false;
                    foreach (int j in columns)
                    {
                        dr[j] = GetValue(sheet.GetRow(i).GetCell(j));
                        if (dr[j] != null && dr[j].ToString() != string.Empty)
                        {
                            hasValue = true;
                        }
                    }
                    if (hasValue)
                    {
                        dt.Rows.Add(dr);
                    }
                }
            }
            return dt;
        }

        /// <summary>
        /// Datable导出成Excel
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="mapping">字段映射</param>
        /// <param name="file"></param>
        public static void TableToExcel(DataTable dt, Dictionary<string, string> mapping, string file)
        {
            DataTable dt2 = new DataTable();

            //表头
            foreach (var item in mapping)
            {
                dt2.Columns.Add(new DataColumn(item.Value));
            }

            //数据
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt2.NewRow();

                foreach (var item in mapping)
                {
                    dr[item.Value] = dt.Rows[i][item.Key];
                }
                dt2.Rows.Add(dr);
            }

            TableToExcel(dt2, file);
        }

        /// <summary>
        /// Datable导出成Excel
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="file">导出路径(包括文件名与扩展名)</param>
        public static void TableToExcel(DataTable dt, string file)
        {
            IWorkbook workbook;
            string fileExt = Path.GetExtension(file).ToLower();
            if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(); } else { workbook = null; }
            if (workbook == null) { return; }
            ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName);

            //表头
            IRow row = sheet.CreateRow(0);
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                ICell cell = row.CreateCell(i);
                cell.SetCellValue(dt.Columns[i].ColumnName);
            }

            ////数据
            //for (int i = 0; i < dt.Rows.Count; i++)
            //{
            //    IRow row1 = sheet.CreateRow(i + 1);
            //    for (int j = 0; j < dt.Columns.Count; j++)
            //    {
            //        ICell cell = row1.CreateCell(j);
            //        cell.SetCellValue(dt.Rows[i][j].ToString());
            //    }
            //}

            //数据
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                row = sheet.CreateRow(i + 1);
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    ICell cell = row.CreateCell(j);
                    cell.SetCellValue(dt.Rows[i][j].ToString());
                    ICellStyle style = workbook.CreateCellStyle();
                    //新建一个字体样式对象
                    IFont font = workbook.CreateFont();
                    font.FontHeightInPoints = 12;
                    //使用SetFont方法将字体样式添加到单元格样式中
                    style.SetFont(font);
                    //将新的样式赋给单元格
                    row.Cells[j].CellStyle = style;

                    //单元格宽度自适应（英文/数字）
                    sheet.AutoSizeColumn(j);
                    //单元格宽度自适应（中文）
                    int columnWidth = sheet.GetColumnWidth(j) / 256;
                    for (int rowNum = 1; rowNum <= sheet.LastRowNum; rowNum++)
                    {
                        IRow currentRow;
                        //当前行未被使用过
                        if (sheet.GetRow(rowNum) == null)
                        {
                            currentRow = sheet.CreateRow(rowNum);
                        }
                        else
                        {
                            currentRow = sheet.GetRow(rowNum);
                        }

                        if (currentRow.GetCell(i) != null)
                        {
                            ICell currentCell = currentRow.GetCell(i);
                            int length = Encoding.Default.GetBytes(currentCell.ToString()).Length;
                            if (columnWidth < length)
                            {
                                columnWidth = length;
                            }
                        }
                    }
                    sheet.SetColumnWidth(j, columnWidth * 270);
                }
            }

            //转为字节数组
            MemoryStream stream = new MemoryStream();
            workbook.Write(stream);
            var buf = stream.ToArray();

            //保存为Excel文件
            using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
            {
                fs.Write(buf, 0, buf.Length);
                fs.Flush();
            }
        }

        /// <summary>
        /// 获取单元格类型
        /// </summary>
        /// <param name="cell"></param>
        /// <returns></returns>
        private static object GetValue(ICell cell)
        {
            if (cell == null)
                return null;
            switch (cell.CellType)
            {
                case CellType.Blank:
                    return null;

                case CellType.Boolean:
                    return cell.BooleanCellValue;

                case CellType.Numeric:
                    return cell.NumericCellValue;

                case CellType.String:
                    return cell.StringCellValue;

                case CellType.Error:
                    return cell.ErrorCellValue;

                case CellType.Formula:
                default:
                    return "=" + cell.CellFormula;
            }
        }
    }
}